import * as signalR from '@microsoft/signalr';
import { ElNotification } from 'element-plus';

export default function (http, receive) {
  let connection;
  let retryCount = 0;
  const maxRetries = 3;
  
  // 创建连接的函数
  const createConnection = (userName) => {
    try {
      // 配置 SignalR 连接
      connection = new signalR.HubConnectionBuilder()
        .withUrl(`${http.ipAddress}message?userName=${userName}`, {
          skipNegotiation: true,
          transport: signalR.HttpTransportType.WebSockets,
          timeout: 100000, // 增加超时时间
        })
        .withAutomaticReconnect([0, 2000, 5000, 10000, 20000]) // 配置重连间隔
        .configureLogging(signalR.LogLevel.Information) // 添加日志
        .build();

      // 启动连接
      const startConnection = async () => {
        try {
          await connection.start();
          console.log('SignalR Connected Successfully');
          retryCount = 0; // 重置重试计数
        } catch (err) {
          console.log('SignalR Connection Error:', err);
          retryCount++;
          
          if (retryCount <= maxRetries) {
            console.log(`Retrying connection... Attempt ${retryCount} of ${maxRetries}`);
            setTimeout(startConnection, 5000); // 5秒后重试
          } else {
            console.log('Max retry attempts reached');
            ElNotification.error({
              title: '连接错误',
              message: '无法连接到消息服务器，请检查网络连接',
              duration: 5000
            });
          }
        }
      };

      // 自动重连成功后的处理
      connection.onreconnected((connectionId) => {
        console.log('SignalR Reconnected:', connectionId);
        ElNotification.success({
          title: '重新连接成功',
          message: '消息服务已恢复连接',
          duration: 3000
        });
      });

      // 开始重连时的处理
      connection.onreconnecting((error) => {
        console.log('SignalR Reconnecting:', error);
        ElNotification.warning({
          title: '正在重新连接',
          message: '正在尝试恢复消息服务连接...',
          duration: 3000
        });
      });

      // 连接断开的处理
      connection.onclose((error) => {
        console.log('SignalR Connection Closed:', error);
        ElNotification.error({
          title: '连接断开',
          message: '消息服务连接已断开',
          duration: 3000
        });
      });

      // 消息处理
      connection.on('ReceiveHomePageMessage', function (data) {
        console.log('Received message:', data);
        if (data && data.title) {
          ElNotification.success({
            title: data.title,
            message: data.message || '',
            type: 'info',
            duration: 3000
          });
          receive && receive(data);
        }
      });

      // 启动连接
      startConnection();

    } catch (error) {
      console.error('SignalR Setup Error:', error);
      ElNotification.error({
        title: '初始化错误',
        message: '消息服务初始化失败',
        duration: 5000
      });
    }
  };

  // 获取用户信息并创建连接
  http.post('api/user/GetCurrentUserInfo')
    .then((result) => {
      if (result && result.data && result.data.userName) {
        createConnection(result.data.userName);
      } else {
        console.warn('No user info available');
        ElNotification.warning({
          title: '警告',
          message: '无法获取用户信息',
          duration: 5000
        });
      }
    })
    .catch((error) => {
      console.error('Failed to get user info:', error);
      ElNotification.error({
        title: '错误',
        message: '获取用户信息失败',
        duration: 5000
      });
    });
}
